<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Cms\Repository;

use Admin\Data\Common;
use Cms\Entity\SingleCms;
use Cms\Repository\QuerySearch\SingleCmsSearch;
use Doctrine\ORM\EntityRepository;
use function Doctrine\ORM\QueryBuilder;

class SingleCmsRepository extends EntityRepository
{
    /**
     * 后台单页列表显示，对应不同模板
     * @return float|int|mixed|string
     */
    public function findSingleCmsList()
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('s')
            ->from(SingleCms::class, 's')
            ->orderBy('s.singleCmsSort', 'ASC')
            ->addOrderBy('s.singleCmsId', 'ASC');

        $template           = Common::readConfigFile('template');
        $pcTemplateStr      = str_replace('/', '-', $template['pcTemplate']);
        $mobileTemplateStr  = str_replace('/', '-', $template['mobileTemplate']);
        switch ($template['displayType']) {
            case 'auto':
                if (!empty($pcTemplateStr)) $query->orWhere('s.templateCode = :pcCode')->setParameter('pcCode', $pcTemplateStr);
                if (!empty($mobileTemplateStr))  $query->orWhere('s.templateCode = :mobCode')->setParameter('mobCode', $mobileTemplateStr);
            break;
            case 'pc':
                $query->where('s.templateCode = :pcCode')->setParameter('pcCode', $pcTemplateStr);
                break;
            case 'mobile':
                $query->where('s.templateCode = :mobCode')->setParameter('mobCode', $mobileTemplateStr);
                break;
        }
        $query->orWhere($query->expr()->isNull('s.templateCode'));

        return $query->getQuery()->getResult();
    }

    /**
     * 后台单页文章列表返回
     * @param array $search
     * @return \Doctrine\ORM\Query
     */
    public function findAllSingleCms(array $search = [])
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('s')
            ->from(SingleCms::class, 's')
            ->orderBy('s.singleCmsId', 'DESC');

        $query = SingleCmsSearch::querySearchData($search, $query);

        return $query->getQuery();
    }
}